from django import http
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.utils.response_code import RETCODE
from users import constants


class ImageCodeView(View):
        # 图片验证
    def get(self, request, uuid):
        '''
        :param uuid: 前端生成的唯一对应码，key值
        :return: ajax请求
        '''
        # 生成验证码，1.captcha获取字母，图片
        text, code, image = captcha.generate_captcha()
        # 将码存入缓存，设置过期
        redis_conn = get_redis_connection('verifications')
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, code)
        # 图片返回
        return http.HttpResponse(image, content_type='image/jpg')
class SmsCodeView(View):
    def get(self, request, mobile):
        '''
        :param request:
        :param mobile: 手机号
        :return:
        '''
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        redis_conn = get_redis_connection('verifications')
        image_code_redis = redis_conn.get('img_%s' % uuid)
        if image_code_redis is None:
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR, 'errmsg':'图片验证码已过期'})
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            # logger.error(e)
            print(e)
        if image_code != image_code_redis.decode():
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR, 'errmsg':'图片验证码输入错误'})



# Create your views here.
